package com.verlet.springbootdemo.simple.disruptor.netty;

import com.lmax.disruptor.RingBuffer;
import io.netty.channel.ChannelHandlerContext;

public class MessageProducer {

    private final String producerId;

    private final RingBuffer<TranslatorDataWapper> ringBuffer;

    public MessageProducer(String producerId, RingBuffer<TranslatorDataWapper> ringBuffer) {
        this.producerId = producerId;
        this.ringBuffer = ringBuffer;
    }

    public void onData(TranslatorData data, ChannelHandlerContext channelHandlerContext) {
        long sequence = ringBuffer.next();
        try {
            TranslatorDataWapper translatorDataWapper = ringBuffer.get(sequence);
            translatorDataWapper.setTranslatorData(data);
            translatorDataWapper.setChannelHandlerContext(channelHandlerContext);
        } finally {
            //发布事件
            //注意，最后的 ringBuffer.publish 方法必须包含在 finally 中以确保必须得到调用；
            //如果某个请求的 sequence 未被提交，将会堵塞后续的发布操作或者其它的 producer。
            ringBuffer.publish(sequence);
        }
    }

}
